package com.whfc.quality.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.whfc.common.exception.BizException;
import com.whfc.common.generator.KeyGeneratorUtil;
import com.whfc.common.result.PageData;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.util.CollectionUtil;
import com.whfc.common.util.PageUtil;
import com.whfc.common.util.RegexUtil;
import com.whfc.quality.dao.QualityIssueMapper;
import com.whfc.quality.dao.QualityIssueTypeMapper;
import com.whfc.quality.dto.QualityIssueDTO;
import com.whfc.quality.dto.QualityIssueTypeDTO;
import com.whfc.quality.entity.QualityIssue;
import com.whfc.quality.entity.QualityIssueType;
import com.whfc.quality.param.QualityIssueAddParam;
import com.whfc.quality.param.QualityIssueEditParam;
import com.whfc.quality.param.QualityIssueTypeAddParam;
import com.whfc.quality.param.QualityIssueTypeEditParam;
import com.whfc.quality.service.QualityIssueService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author : qzexing
 * @version : 1.0
 * @date : 2020-07-30 19:33
 */
@DubboService(interfaceClass = QualityIssueService.class, version = "1.0.0", timeout = 5000)
public class QualityIssueServiceImpl implements QualityIssueService {

    @Autowired
    private QualityIssueMapper qualityIssueMapper;

    @Autowired
    private QualityIssueTypeMapper qualityIssueTypeMapper;

    @Override
    public List<QualityIssueTypeDTO> issueTypeList(Integer deptId, String keyword) throws BizException {
        List<QualityIssueTypeDTO> issueTypeList = qualityIssueTypeMapper.selectIssueTypeList(deptId, keyword);
        List<QualityIssueDTO> issueList = qualityIssueMapper.selectByDeptId(deptId);
        return parseTree(issueTypeList, issueList);
    }

    @Override
    public void addIssueType(QualityIssueTypeAddParam addParam) throws BizException {
        QualityIssueType issueType = new QualityIssueType();
        String code = addParam.getCode();
        if (!RegexUtil.isInteger(code)) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "编码格式错误.");
        }

        if (addParam.getPid() != null) {
            QualityIssueType pIssueType = qualityIssueTypeMapper.selectByPrimaryKey(addParam.getPid());
            if (pIssueType == null) {
                throw new BizException(ResultEnum.FAILURE.getCode(), "父问题类型节点不存在");
            }
            if (!qualityIssueMapper.selectByIssueTypeId(addParam.getPid()).isEmpty()) {
                throw new BizException(ResultEnum.FAILURE.getCode(), "父问题类型节点下已存在数据不能添加子节点");
            }
            code = pIssueType.getCode() + "." + code;
            issueType.setPid(pIssueType.getId());
            issueType.setLevel(pIssueType.getLevel() + 1);
        } else {
            issueType.setPid(0L);
            issueType.setLevel(1);
        }
        Integer deptId = addParam.getDeptId();
        if (qualityIssueTypeMapper.selectIssueTypeByCode(deptId, code) != null) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "该编码已存在.");
        }
        issueType.setId(KeyGeneratorUtil.genLongId());
        issueType.setDeptId(deptId);
        issueType.setCode(code);
        issueType.setName(addParam.getName());
        qualityIssueTypeMapper.insertSelective(issueType);
    }

    @Override
    public void editIssueType(QualityIssueTypeEditParam editParam) throws BizException {
        String code = editParam.getCode();
        if (!RegexUtil.isInteger(code)) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "编码格式错误.");
        }
        QualityIssueType qualityIssueType = qualityIssueTypeMapper.selectByPrimaryKey(editParam.getIssueTypeId());
        if (qualityIssueType == null) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "该问题类型不存在.");
        }

        QualityIssueType pIssueType = qualityIssueTypeMapper.selectByPrimaryKey(qualityIssueType.getPid());
        if (pIssueType != null) {
            code = pIssueType.getCode() + "." + code;
        }
        if (qualityIssueTypeMapper.selectIssueTypeByCode(qualityIssueType.getDeptId(), code) != null && !qualityIssueType.getCode().equals(code)) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "该编码已存在.");
        }
        Integer length = qualityIssueType.getCode().length();
        List<QualityIssueType> issueTypes = qualityIssueTypeMapper.selectLikeCode(qualityIssueType.getCode() + ".");
        for (QualityIssueType issueType : issueTypes) {
            issueType.setCode(code + issueType.getCode().substring(length));
            qualityIssueTypeMapper.updateByPrimaryKeySelective(issueType);
        }
        qualityIssueTypeMapper.updateById(editParam.getIssueTypeId(), code, editParam.getName());
    }

    @Override
    public void delIssueType(Long issueTypeId) throws BizException {
        List<QualityIssueType> issueType = qualityIssueTypeMapper.selectByPid(issueTypeId);
        List<QualityIssueDTO> issues = qualityIssueMapper.selectByIssueTypeId(issueTypeId);
        if (!issueType.isEmpty() || !issues.isEmpty()) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "有子节点存在无法删除.");
        }
        qualityIssueTypeMapper.logicDel(issueTypeId);
    }

    @Override
    public List<QualityIssueDTO> issueList(Long issueTypeId) throws BizException {
        return qualityIssueMapper.selectByIssueTypeId(issueTypeId);
    }

    @Override
    public PageData<QualityIssueDTO> issueList(Long issueTypeId, Integer pageNum, Integer pageSize) throws BizException {
        PageHelper.startPage(pageNum, pageSize);
        List<QualityIssueDTO> list = qualityIssueMapper.selectByIssueTypeId(issueTypeId);
        if (list == null) {
            return new PageData<>();
        }
        PageHelper.clearPage();
        return PageUtil.pageData(PageInfo.of(list));
    }

    @Override
    public List<QualityIssueDTO> issueHistoryList(Integer deptId, Integer pageSize) throws BizException {
        return qualityIssueMapper.selectHistoryByDeptIdAndPageSize(deptId, pageSize);
    }

    @Override
    public List<QualityIssueDTO> issueList(Integer deptId) throws BizException {
        return qualityIssueMapper.selectByDeptId(deptId);
    }

    @Override
    public void addIssue(QualityIssueAddParam addParam) throws BizException {
        QualityIssueType issueType = qualityIssueTypeMapper.selectByPrimaryKey(addParam.getIssueTypeId());
        if (issueType == null) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "该问题类型不存在.");
        }
        List<QualityIssueType> issueTypes = qualityIssueTypeMapper.selectByPid(issueType.getId());
        if (!issueTypes.isEmpty()) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "该问题类型下存在子节点无法添加明细.");
        }
        QualityIssue issue = new QualityIssue();
        BeanUtils.copyProperties(addParam, issue);
        issue.setIssueTypeName(issueType.getName());
        issue.setId(KeyGeneratorUtil.genLongId());
        issue.setDeptId(issueType.getDeptId());
        qualityIssueMapper.insertSelective(issue);
    }

    @Override
    public void editIssue(QualityIssueEditParam editParam) throws BizException {
        if (qualityIssueMapper.selectByPrimaryKey(editParam.getIssueId()) == null) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "该问题明细不存在.");
        }
        qualityIssueMapper.updateByIssueId(editParam.getIssueId(), editParam.getContent(), editParam.getRequire(), editParam.getDuration());
    }

    @Override
    public void delIssue(Long issueId) throws BizException {
        qualityIssueMapper.logicDel(issueId);
    }

    @Override
    public void disableOrEnabledIssue(Long issueId, Integer enable) {
        qualityIssueMapper.disableOrEnabledIssue(issueId, enable);
    }

    @Override
    public void deleteBatch(List<Integer> idList) {
        if(CollectionUtils.isEmpty(idList)){
            return;
        }
        qualityIssueMapper.deleteBatch(idList);
    }

    /**
     * 树形处理数据
     *
     * @param list 问题类型列表
     * @return 问题类型列表
     */
    private List<QualityIssueTypeDTO> parseTree(List<QualityIssueTypeDTO> list, List<QualityIssueDTO> issueDTOS) {
        Map<Long, List<QualityIssueDTO>> issueDTOMap = new HashMap<>();
        issueDTOS.forEach(issueDTO -> {
            List<QualityIssueDTO> qualityIssueDTOS;
            if (!issueDTOMap.containsKey(issueDTO.getIssueTypeId())) {
                qualityIssueDTOS = new ArrayList<>();
            } else {
                qualityIssueDTOS = issueDTOMap.get(issueDTO.getIssueTypeId());
            }
            qualityIssueDTOS.add(issueDTO);
            issueDTOMap.put(issueDTO.getIssueTypeId(), qualityIssueDTOS);
        });
        list.forEach(issueTypeDTO -> {
            if (issueDTOMap.containsKey(issueTypeDTO.getIssueTypeId())) {
                issueTypeDTO.setIssues(issueDTOMap.get(issueTypeDTO.getIssueTypeId()));
            }
        });
        // 1、获取第一级节点
        Map<Long, List<QualityIssueTypeDTO>> issueTypeMap = list.stream().collect(Collectors.groupingBy(QualityIssueTypeDTO::getPid));
        list.forEach(issuetypeDTO -> issuetypeDTO.setChildren(issueTypeMap.get(issuetypeDTO.getIssueTypeId())));
        List<QualityIssueTypeDTO> result = list.stream().filter(v -> v.getPid().equals(0L)).collect(Collectors.toList());

        return result;
    }

}
